<template>
  <div class="table-container">
    <vab-query-form>
      <vab-query-form-left-panel>
        <el-button icon="el-icon-download" type="primary" @click="handleAdd">下载文件</el-button>
        <el-upload
          :on-success="successupload"
          :on-progress="uploadprogress"
          :on-error="errorupload"
          :data="data"
          :auto-upload="true"
          class="upload-demo"
          :action="baseURL + '/Upload/ExcelImport'"
          name="file"
          accept="xlsx"
          :show-file-list="false"
          :file-list="fileList"
        >
          <el-button icon="el-icon-upload" type="warning" @click="uploadFile">导入文件</el-button>
        </el-upload>
      </vab-query-form-left-panel>
    </vab-query-form>
    <el-table border ref="tableSort" v-loading="listLoading" :data="list" :element-loading-text="elementLoadingText" :height="height">
      <el-table-column prop="id" label="ID" width="180"></el-table-column>
      <el-table-column label="分数" prop="score" show-overflow-tooltip />
      <el-table-column label="人数" prop="ranKingNum" show-overflow-tooltip />
      <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip />
    </el-table>
  </div>
</template>

<script>
  import { baseURL } from '@/config'
  import axios from 'axios'
  import { GetScoreRangeList, ScoreRange } from '@/api/table'
  import TableEdit from './components/TableEdit'

  export default {
    name: 'ComprehensiveTable',
    components: {
      TableEdit,
    },
    data() {
      return {
        Loading: null,
        baseURL: baseURL,
        list: [],
        fileList: [],
        listLoading: true,
        background: true,
        elementLoadingText: '正在加载...',
        timeOutID: null,
        data: {
          type: 1,
        },
      }
    },
    computed: {
      height() {
        return this.$baseTableHeight() + 50
      },
    },
    created() {
      this.fetchData()
    },
    beforeDestroy() {
      clearTimeout(this.timeOutID)
    },
    mounted() {},
    methods: {
      uploadprogress() {
        this.Loading = this.$baseColorfullLoading(1)
      },
      successupload(e) {
        console.log(e)
        this.Loading.close()
        this.fetchData()
      },
      errorupload(e) {
        console.log(e)

        this.Loading.close()
        this.fetchData()
      },
      uploadFile() {},
      async handleAdd() {
        try {
          // 发送 GET 请求以下载 Excel 文件
          const response = await axios.get(baseURL + '/Download/ScoreRange', {
            responseType: 'blob', // 指定响应类型为 blob
            headers: {
              'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            },
          })

          // 检查响应状态
          if (response.status !== 200) {
            throw new Error('网络响应不正常')
          }

          // 获取文件名
          const disposition = response.headers['content-disposition']
          let fileName = '分数段列表.xlsx' // 默认文件名
          if (disposition) {
            const matches = /filename[^;=\n]*=((['"]).*?\2|([^;\n]*))/i.exec(disposition)
            if (matches != null && matches[1]) {
              fileName = decodeURIComponent(matches[1].replace(/['"]/g, '')) // 使用 decodeURIComponent 解码
            }
          }

          // 创建 Blob 对象并生成下载链接
          const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
          const url = window.URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.href = url
          a.download = fileName // 设置下载文件名
          document.body.appendChild(a)
          a.click() // 触发下载
          a.remove() // 下载后移除链接
          window.URL.revokeObjectURL(url) // 释放 Blob URL
        } catch (error) {
          console.error('下载文件时出错:', error)
        }
      },
      handleEdit(row) {
        this.$refs['edit'].showEdit(row)
      },
      async fetchData() {
        this.listLoading = true
        const { data } = await GetScoreRangeList()
        this.list = data
        this.timeOutID = setTimeout(() => {
          this.listLoading = false
        }, 500)
      },
    },
  }
</script>
